package com.base;

/**
 * 1. wait() 函数
 */
public class Demo02 {

    // 资源
    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();


    public static void main(String[] args) throws InterruptedException {

        // 线程A
        Thread threadA = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    // 获取resourceA共享资源监视器锁
                    synchronized (resourceA) {
                        System.out.println("ThreadA get resourceA lock");

                        // 获取resourceB共享资源监视器锁
                        synchronized (resourceB) {
                            System.out.println("ThreadA get resourceB lock");
                            //线程A阻塞, 并释放获取到的resourceA的锁
                            System.out.println("ThreadA release resourceA lock");
                            // (调用共享变量的wait(), 此线程会被阻塞挂起
                            resourceA.wait(4000);
                            //resourceA.wait();

                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }


            }
        });


        // 线程B
        Thread threadB = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    // 休眠1s
                    Thread.sleep(5000);
                    // 获取共享资源A的监视器锁
                    synchronized (resourceA) {
                        System.out.println("ThreadB get resourceA lock");

                        System.out.println("ThreadB try get resourceB lock ...");

                        // 如何让线程B获取到resourceB lock?

                        synchronized (resourceB) {

                            System.out.println("ThreadB get resourceB lock");

                            // 阻塞线程B, 并释放获取得到的resourceA的锁\
                            System.out.println("ThreadB release resourceA lock");
//                            resourceB.wait();
                            resourceB.wait(5000);

                        }
                    }

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });


        // 启动线程
        threadA.start();
        threadB.start();

        // 等待线程结束
        threadA.join();
        threadB.join();

        System.out.println("over");


    }
}
